import yaml
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
from selenium.common.exceptions import WebDriverException


class BasePage:
    def __init__(self):
        caps = yaml.safe_load(open("../app_first_pratice/caps.yaml"))['caps']
        self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub',caps)
        self.driver.implicitly_wait(5)

    def swipe_search(self,num,textname):
        for i in range(num):
            try:
                self.driver.find_element(MobileBy.XPATH,f"//*[@text={textname}]")
            except:
                rect = self.driver.get_window_size()
                width = rect["width"]
                height = rect["height"]
                x_start = width/2
                y_start = height * 0.8
                x_end = width/2
                y_end = height *0.4
                self.driver.swipe(x_start,y_start,x_end,y_end)
                self.driver.find_element(MobileBy.XPATH,f"//*[@text={textname}]")
            if i == num-1:
                raise WebDriverException(f"查找{num}次，未找到{textname}元素,请重新查找")
    # 查找元素
    def find(self,by,locator=None):
        if locator==None:
            ele = self.driver.find_element(*by)
        else:
            ele = self.driver.find_element(by=by,value=locator)

        return ele
    # 获取toast信息
    def get_toast_message(self):
        toast_message = self.driver.find_element(MobileBy.XPATH,"//*[@class='android.widget.Toast']").get_attribute("text")
        return toast_message

    def pares_yaml(self,path,funcname):
        with open(path,encoding='utf-8') as f:
            data = yaml.safe_load(f)
            steps = data[funcname]
        self.pares(steps)

    def pares(self,steps):
        for step in steps:
            if step['action'] == 'click':
                self.find(step['by'],step['locator']).click()
            elif step['action'] == 'send':
                self.find(step['by'],step['locator']).send_keys(step['content'])
